package com.sqk.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sqk.reggie.common.Result;
import com.sqk.reggie.dto.SetmealDto;
import com.sqk.reggie.pojo.Category;
import com.sqk.reggie.pojo.Dish;
import com.sqk.reggie.pojo.Setmeal;
import com.sqk.reggie.pojo.SetmealDish;
import com.sqk.reggie.service.CategoryService;
import com.sqk.reggie.service.DishService;
import com.sqk.reggie.service.SetmealDishService;
import com.sqk.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 套餐管理
 */
@Slf4j
@RestController
@RequestMapping("/setmeal")
public class SetmealController {

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private DishService dishService;

    @Autowired
    private CacheManager cacheManager;

    /**
     * 套餐分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @RequestMapping("/page")
    public Result<Page<SetmealDto>> selectPage(int page, int pageSize, String name) {
        Page<Setmeal> setmealPage = new Page<>(page, pageSize);
        Page<SetmealDto> setmealDtoPage = new Page<>();

        //Setmeal的分页查询
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(name != null, Setmeal::getName, name);
        queryWrapper.orderByDesc(Setmeal::getCreateTime);
        setmealService.page(setmealPage, queryWrapper);

        //将Setmeal的分页查询信息复制到SetmealDto的分页查询中，
        // 但不复制Setmeal的信息(即 “records”中的信息，分页查询的数据信息储存在Page的records字段中)
        BeanUtils.copyProperties(setmealPage, setmealDtoPage, "records");

        List<Setmeal> setmealList = setmealPage.getRecords();
        List<SetmealDto> setmealDtoList = setmealList.stream().map(item -> {
            SetmealDto setmealDto = new SetmealDto();

            BeanUtils.copyProperties(item, setmealDto);

            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            String categoryName = category.getName();

            setmealDto.setCategoryName(categoryName);

            return setmealDto;

        }).collect(Collectors.toList());

        setmealDtoPage.setRecords(setmealDtoList);

        return Result.success(setmealDtoPage);
    }

    /**
     * 保存套餐信息
     * @param setmealDto
     * @return
     */
    @PostMapping
    @CacheEvict(value = "setmealCache", allEntries = true)
    public Result<String> save(@RequestBody SetmealDto setmealDto){
        setmealService.saveWithDish(setmealDto);
        return Result.success("添加成功!");
    }

    /**
     * 删除套餐，同时删除套餐对应的菜品
     * @param ids
     * @return
     */
    @DeleteMapping
    @CacheEvict(value = "setmealCache", allEntries = true)
    public Result<String> removeSetmeal(String ids){
        setmealService.removeMealWithDish(ids);
        return Result.success("删除成功");

    }

    /**
     * 修改套餐的状态
     * @param ids
     * @param status
     * @return
     */
    @PostMapping("/status/{status}")
    @CacheEvict(value = "setmealCache", allEntries = true)
    public Result<String> updateStatus(String ids, @PathVariable Integer status){
        //拆分ids
        String[] idsA = ids.split(",");

        Setmeal setmeal = new Setmeal();

        Arrays.stream(idsA).forEach(item ->{
            long dishId = Long.parseLong(item);
            setmeal.setId(dishId);
            setmeal.setStatus(status);
            setmealService.updateById(setmeal);
        });

        return Result.success("修改成功!");
    }

    /**
     * 根据id进行setmealDto数据的回显
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<SetmealDto> getById(@PathVariable Long id){
        SetmealDto setmealDto = setmealService.getMealById(id);
        return Result.success(setmealDto);
    }

    /**
     * 修改套餐
     * @param setmealDto
     * @return
     */
    @PutMapping
    @CacheEvict(value = "setmealCache", allEntries = true)
    public Result<String> updateMeal(@RequestBody SetmealDto setmealDto){
        setmealService.updateMealWithDish(setmealDto);
        return Result.success("修改成功");
    }

    /**
     * 移动端套餐列表
     * @param setmeal
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = "setmealCache", key = "#setmeal.categoryId + '_' + #setmeal.status")
    public Result<List<SetmealDto>> list(Setmeal setmeal){

        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(setmeal.getCategoryId() != null,Setmeal::getCategoryId,setmeal.getCategoryId());
        queryWrapper.eq(setmeal.getStatus() != null, Setmeal::getStatus,setmeal.getStatus());

        List<Setmeal> setmeals = setmealService.list(queryWrapper);
        List<SetmealDto> setmealDtoList = setmeals.stream().map(item -> {
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(item, setmealDto);

            LambdaQueryWrapper<SetmealDish> setmealDtoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            setmealDtoLambdaQueryWrapper.eq(SetmealDish::getSetmealId,item.getId());
            setmealDtoLambdaQueryWrapper.orderByDesc(SetmealDish::getCreateTime);
            List<SetmealDish> setmealDishes = setmealDishService.list(setmealDtoLambdaQueryWrapper);

            setmealDto.setSetmealDishes(setmealDishes);
            return setmealDto;
        }).collect(Collectors.toList());

        return Result.success(setmealDtoList);
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @GetMapping("/dish/{id}")
    public Result<List<Dish>> getSetmealById(@PathVariable Long id){

        SetmealDto mealById = setmealService.getMealById(id);
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId,id);
        queryWrapper.orderByDesc(SetmealDish::getCreateTime);
        List<SetmealDish> setmealDishes = setmealDishService.list(queryWrapper);
        List<Long> dishIds = setmealDishes.stream().map(item ->{
            //根据dishId获取dish的id
            Long dishId = item.getDishId();

            return dishId;
        }).collect(Collectors.toList());

        List<Dish> dishes = dishService.listByIds(dishIds);

        return Result.success(dishes);
    }
}
